package com.mx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mx.mapper.*;
import com.mx.pojo.*;
import com.mx.pojo.VO.ArticleVO;
import com.mx.utils.QiNiuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    TagMapper tagMapper;

    @Autowired
    ArticleTagMapper articleTagMapper;

    @Autowired
    CommentMapper commentMapper;
    @Autowired
    StarMapper starMapper;
    @Autowired
    AttentionMapper attentionMapper;

    @RequestMapping("/attention")
    public String attention(Integer id, HttpSession session, Model model) {
        if (id == null)
            id = 1;
        HashMap<String, Object> map1 = new HashMap<>();
        User user2 = (User) session.getAttribute("user");
        map1.put("masteruid", user2.getId());
        List<Attention> attentions = attentionMapper.selectByMap(map1);
        List<Integer> list = new ArrayList<>();
        for (Attention attention : attentions) {
            list.add(attention.getDoneuid());
        }

        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.in("uid", list);
        articleQueryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, articleQueryWrapper);
        List<Article> articles = articlePage.getRecords();

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user.getName()));
        }

        //如果已经登录  点赞收藏情况查询
        User user1 = (User) session.getAttribute("user");
        if (user1 != null) {
            for (ArticleVO articleVO : articleVOS) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getId());//     我
                map.put("aid", articleVO.getId());//关注的文章
                List<Star> stars = starMapper.selectByMap(map);
                if (stars != null && stars.size() != 0) {
                    Star star = stars.get(0);
                    if (star.getStar() != 0) {
                        articleVO.isStar = true;

                    }
                    if (star.getAgree() != 0) {
                        articleVO.isAgree = true;
                    }
                }
            }
        }

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        return "attention";
    }


    @GetMapping("/addArticle")
    public String toAddArticle(Integer id, Model model) {
        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);
        if (id == null)//跳转添加博客
        {
            List<Integer> articleTags = new ArrayList<>();
            model.addAttribute("oldTags", articleTags);
            return "user/addArticle";
        } else //跳转编辑博客
        {
            Article article = articleMapper.selectById(id);
            Map<String, Object> map = new HashMap<>();
            map.put("aid", id);
            List<ArticleTag> articleTags = articleTagMapper.selectByMap(map);
            ArrayList<Integer> integers = new ArrayList<>();
            for (ArticleTag articleTag : articleTags) {
                integers.add(articleTag.getTid());
            }
            System.out.println("oldTags" + integers);
            model.addAttribute("article", article);
            model.addAttribute("oldTags", integers);
            return "user/addArticle";
        }
    }

    @PostMapping("/addArticle")
    public String addArticle(HttpSession session, Integer tags[], Article article, @RequestParam("file") MultipartFile file) throws IOException {
        String path = null;
        // 获取文件的名称
        String fileName = file.getOriginalFilename();
        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = UUID.randomUUID().toString() + fileName;
        if (!file.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            path = QiNiuUtil.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
        }
        article.setDate(new Date());
        article.setImage(path);
        User user = (User) session.getAttribute("user");
        article.setUid(user.getId());
        article.setId(0);
        article.setAgree(0);
        System.out.println("添加文章：" + article);

        articleMapper.insert(article);

        List<Article> all = articleMapper.selectList(null);
        Article temp = all.get(all.size() - 1);

        if (tags != null) {
            for (Integer tag : tags) {
                articleTagMapper.insert(new ArticleTag(0, temp.getId(), tag));
            }
        }
        return "redirect:/user/main";

    }

    @PostMapping("/personal")
    public String personal(HttpSession session, String name, String introduction, @RequestParam("file") MultipartFile file) throws IOException {
        String path = null;
        // 获取文件的名称
        String fileName = file.getOriginalFilename();
        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = UUID.randomUUID().toString() + fileName;
        if (!file.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            path = QiNiuUtil.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
        }
        User user = (User) session.getAttribute("user");
        user.setName(name);
        if (path != null)
            user.setAvatar(path);
        user.setIntroduction(introduction);
        userMapper.updateById(user);
        return "redirect:/manage?uid=" + user.getId();

    }

    @RequestMapping("/collection")
    public String collection(Integer id, Model model, HttpSession session) {
        if (id == null)
            id = 1;

        User user = (User) session.getAttribute("user");

        List<Tag> tags = tagMapper.selectList(null);
        model.addAttribute("tags", tags);

        QueryWrapper<Star> starQueryWrapper = new QueryWrapper<>();
        starQueryWrapper.eq("uid", user.getId());//我
        starQueryWrapper.ge("star", 1);//收藏的文章
        List<Star> stars1 = starMapper.selectList(starQueryWrapper);
        ArrayList<Integer> integers = new ArrayList<>();
        for (Star star : stars1) {
            integers.add(star.getAid());
        }

        ArrayList<ArticleVO> articleVOS = new ArrayList<>();

        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.in("id", integers);
        articleQueryWrapper.orderByDesc("id");

        Page<Article> articlePage = articleMapper.selectPage(objectPage, articleQueryWrapper);
        List<Article> articles = articlePage.getRecords();

        for (Article article : articles) {
            if (article.getContent().length() >= 221) {
                article.setContent(article.getContent().substring(0, 220) + "...");
            }
            User user1 = userMapper.selectById(article.getUid());
            articleVOS.add(new ArticleVO(article, user1.getName()));
        }


        for (ArticleVO articleVO : articleVOS) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", user.getId());//     我
            map.put("aid", articleVO.getId());//关注的文章
            List<Star> stars = starMapper.selectByMap(map);
            if (stars != null && stars.size() != 0) {
                Star star = stars.get(0);
                if (star.getStar() != 0) {
                    articleVO.isStar = true;

                }
                if (star.getAgree() != 0) {
                    articleVO.isAgree = true;
                }
            }
        }

        model.addAttribute("articles", articleVOS);
        model.addAttribute("articlePage", articlePage);
        return "collection";
    }

    @PostMapping("/updateArticle")
    public String updateArticle(Integer tags[], Article article, @RequestParam("file") MultipartFile file) throws
            IOException {
        String path = null;
        if (file.isEmpty()) {
            System.err.println("上传的图片为空");
            article.setImage(articleMapper.selectById(article.getId()).getImage());
        } else {
            String fileName = file.getOriginalFilename();
            String imgName = UUID.randomUUID().toString() + fileName;
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            path = QiNiuUtil.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
            article.setImage(path);
        }

        article.setDate(new Date());

        articleMapper.updateById(article);
        HashMap<String, Object> map = new HashMap<>();
        map.put("aid", article.getId());
        articleTagMapper.deleteByMap(map);

        if (tags != null) {
            for (Integer tag : tags) {
                articleTagMapper.insert(new ArticleTag(0, article.getId(), tag));
            }
        }
        return "redirect:/user/main";
    }


    @GetMapping("/manage")
    public String manage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return "redirect:/manage?uid=" + user.getId();
    }


    @RequestMapping("/phone")
    public String phone() {
        return "user/addArticle_phone";
    }

    @RequestMapping("/deleteArticle")
    public String deleteArticle(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("aid", id);
        //查找并删除出该文章绑定的标签
        List<ArticleTag> articleTags = articleTagMapper.selectByMap(map);
        for (ArticleTag articleTag : articleTags) {
            articleTagMapper.deleteById(articleTag.getId());
        }

        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("aid", id);
        starMapper.deleteByMap(map1);

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("aid", id);
        commentMapper.deleteByMap(map2);

        //然后再删除文章
        articleMapper.deleteById(id);
        return "redirect:/user/main";
    }

    @RequestMapping("/deleteArticle2")
    public String deleteArticle2(Integer id, String location) {
        Map<String, Object> map = new HashMap<>();
        map.put("aid", id);
        //查找并删除出该文章绑定的标签
        List<ArticleTag> articleTags = articleTagMapper.selectByMap(map);
        for (ArticleTag articleTag : articleTags) {
            articleTagMapper.deleteById(articleTag.getId());
        }
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("aid", id);
        starMapper.deleteByMap(map1);

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("aid", id);
        commentMapper.deleteByMap(map2);

        //然后再删除文章
        articleMapper.deleteById(id);

        if (location.equals("dashboard"))
            return "redirect:/";

        if (location.equals("manage"))
            return "redirect:/user/manage";

        return "redirect:/user/manage";
    }


    @RequestMapping("/main")
    public String main(Integer id, Model model, HttpSession session) {
        //id为页数
        if (id == null)
            id = 1;
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        User user = (User) session.getAttribute("user");
        queryWrapper.eq("uid", user.getId());
        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        queryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, queryWrapper);
        //查出uid的作者的文章
        List<Article> articles = articlePage.getRecords();


        model.addAttribute("articles", articles);
        model.addAttribute("articlePage", articlePage);
        return "user/main";
    }


    //markdown图片上传
    @RequestMapping("/upload")
    @ResponseBody
    public HashMap<String, Object> upload(@RequestParam("editormd-image-file") MultipartFile file, Model model) throws
            IOException {
        System.out.println("进入upload方法");
        String downloadPath = "";
        String path = null;
        // 获取文件的名称
        String fileName = file.getOriginalFilename();
        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = UUID.randomUUID().toString() + fileName;
        if (!file.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            path = QiNiuUtil.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("url", path);
        map.put("success", 1);
        map.put("message", "upload success!");

        return map;
    }

    @RequestMapping("/comment")
    public String comment(Comment comment, HttpSession session) {
        comment.setDate(new Date());
        User user = (User) session.getAttribute("user");
        comment.setName(user.getName());
        comment.setId(0);
        System.out.println(comment);
        commentMapper.insert(comment);
        return "redirect:/detail?id=" + comment.getAid() + "#a1";
    }


    @RequestMapping("/admin")
    public String admin (Integer id, Model model, HttpSession session){
        //id为页数
        if (id == null)
            id = 1;
        User user = (User) session.getAttribute("user");
        if(!user.getUsername().equals("admin"))
        {
            return "redirect:/user/main";
        }
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        //分页
        Page<Article> objectPage = new Page<>(id, 5);
        queryWrapper.orderByDesc("id");
        Page<Article> articlePage = articleMapper.selectPage(objectPage, null);
        //查出uid的作者的文章
        List<Article> articles = articlePage.getRecords();


        model.addAttribute("articles", articles);
        model.addAttribute("articlePage", articlePage);
        return "user/admin";
    }
}
